## 
rm(list = ls())

library(tidyverse)
library(fixest)

source("code/helper_functions.R")

## Load data

btw <- readRDS("data/data_main.RDS") %>%
    mutate(treat_categorical4 = factor(treat_categorical4,
        levels = c(
            "NoChange",
            "DecAndInc",
            "Increase",
            "Decrease"
        )
    )) %>%
    filter(!year == 2013) %>%
    mutate(y_new = small_party_zweit_diff - left_zweit_diff)

## Municipal data

muni <- readRDS('data/data_main_municipal.RDS') %>%
  mutate(treat_categorical4 = factor(treat_categorical4,
                                     levels = c('NoChange',
                                                'DecAndInc',
                                                'Increase',
                                                'Decrease')))

## Models comparing results w/ and w/o missing covars

cvars <- c(
    "covar_pop_total_diff",
    "covar_gdp_pc_diff"
)

## df w/ complete covars

nm <- btw %>%
    filter(!is.na(covar_pop_total_diff) &
        !is.na(covar_gdp_pc_diff))

## Models 


m1 <- feols(polar_bund_alt_diff ~ treat_categorical4 | year,
    data = btw,
    cluster = ~county_id_2018
)

m2 <- feols(small_party_zweit_diff ~ treat_categorical4 | year,
    data = btw,
    cluster = ~county_id_2018
)

m3 <- feols(
    polar_bund_alt_diff ~ treat_categorical4 +
        covar_pop_total_diff +
        covar_gdp_pc_diff | year,
    data = btw,
    cluster = ~county_id_2018
)

m4 <- feols(
    small_party_zweit_diff ~ treat_categorical4 +
        covar_pop_total_diff +
        covar_gdp_pc_diff | year,
    data = btw,
    cluster = ~county_id_2018
)

m5 <- feols(polar_bund_alt_diff ~ treat_categorical4 | year,
    data = nm,
    cluster = ~county_id_2018
)

m6 <- feols(small_party_zweit_diff ~ treat_categorical4 | year,
    data = nm,
    cluster = ~county_id_2018
)


mlist <- list(m1, m5, m3, m2, m6, m4)

## Table A.6

etable(mlist,
    keep = "exit", tex = T, digits = 3,
    fitstat = c("r2", "n"),
    style.tex = style.tex("qje"),
    dict = c(
        treat_categorical4Decrease = "Newspaper exit",
        year = "Year FE"
    ),
    extralines = list(
        "Sample" = c(
            "Full", "Non-missing covariates", "Non-missing covariates",
            "Full", "Non-missing covariates", "Non-missing covariates"
        ),
        "Covariates" = c(
            "No", "No", "Yes",
            "No", "No", "Yes"
        )
    ), title = "Effects conditional on sample defined by non-missing covariates"
)

